/*
 * @author: Victor
 * @Date: 2021-04-09 14:49:12
 * @LastEditTime: 2021-04-09 16:10:04
 */
window.addEventListener('load', function () {
  //需求:
  // 1 显示隐藏
  // 2 遮挡层跟随鼠标移动(只能在小盒子范围内)
  // 3 大图片也跟随移动

  // 获取元素
  var preview = document.querySelector('.preview_img');
  var mask = document.querySelector('.mask');
  var big = preview.querySelector('.big');
  var bigImg = big.querySelector('img');
  // preview及mask的宽高,mask及bigImg能移动的最大距离
  var w = preview.clientWidth, //不含边框的宽度
    h = preview.clientHeight, //不含边框的高度
    maskW, //mask宽度
    maskH, //mask高度
    maskMaxX, //mask能移动的最大水平距离
    maskMaxY, //mask能移动的最大垂直距离
    bigMaxX, //大图片能移动最大水平距离
    bigMaxY; //大图片能移动的最大垂直距离
  // 鼠标移入preview显示mask及big移出时隐藏
  preview.addEventListener('mouseover', function () {
    mask.style.display = 'block';
    big.style.display = 'block';
    // 不能通过offsetWidth/Height直接获取隐藏元素的宽高，需要显示之后才能获取
    maskW = mask.offsetWidth;
    maskH = mask.offsetHeight;
    maskMaxX = w - maskW;
    maskMaxY = h - maskH;
    bigMaxX = bigImg.offsetWidth - big.offsetWidth;
    bigMaxY = bigImg.offsetHeight - big.offsetHeight;
    // console.log(maskMaxX, maskMaxY, bigMaxX, bigMaxY);
  });
  preview.addEventListener('mouseout', function () {
    mask.style.display = 'none';
    big.style.display = 'none';
  });
  // 移动鼠标时遮挡层跟随鼠标移动(只能在小盒子范围内)
  preview.addEventListener('mousemove', function (e) {
    // 用鼠标坐标控制 mask的 left及top
    var left = e.pageX - this.offsetLeft - maskW / 2;
    var top = e.pageY - this.offsetTop - maskH / 2;
    if (left < 0) {
      left = 0;
    } else if (left >= maskMaxX) {
      left = maskMaxX;
    }
    if (top < 0) {
      top = 0;
    } else if (top >= maskMaxY) {
      top = maskMaxY;
    }
    mask.style.left = left + 'px';
    mask.style.top = top + 'px';

    //计算大图片的left及top并赋值给大图片
    var bigLeft = (-left / maskMaxX) * bigMaxX;
    var bigTop = (-top / maskMaxY) * bigMaxY;
    bigImg.style.left = bigLeft + 'px';
    bigImg.style.top = bigTop + 'px';
  });
});
